use std::net::{SocketAddr, UdpSocket};
use std::str;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    test_broadcast()?;
    Ok(())
}

fn test_broadcast() -> Result<(), Box<dyn std::error::Error>> {
    let port = 6112;
    
    // 绑定到127.0.2.1:6112
    let bind_addr: SocketAddr = "127.0.2.1:6112".parse()?;
    let socket = UdpSocket::bind(bind_addr)?;
    socket.set_broadcast(true)?; // 允许广播
    
    let broadcast_addr: SocketAddr = "255.255.255.255:6112".parse()?;
    
    let text = "我的 自定 义房间 A";
    let custom_text = text.as_bytes();
    
    // 1. 创建31字节数组，默认填充0x20（空格）
    let mut padded_bytes = [0x20u8; 31];
    
    // 2. 拷贝原数据（确保不越界）
    let copy_length = std::cmp::min(custom_text.len(), 31);
    padded_bytes[..copy_length].copy_from_slice(&custom_text[..copy_length]);
    
    // 3. 转换为十六进制字符串
    let mut hex_builder = String::new();
    for &b in &padded_bytes {
        hex_builder.push_str(&format!("{:02x} ", b));
    }
    
    // 构建完整的数据包（与 Java 版本完全一致，包括尾部空格）
    let hex_string = format!(
        "f7 30 93 00 50 58\n\
         33 57 1b 00 00 00 01 00 00 00 6e 8d b4 00 {} 00 00 01\n\
         03 49 07 01 01 a1 01 b9 49 01 13 8f e7 6f 4d 8b\n\
         61 71 73 5d 29 33 29 ad 43 6f 6f 75 79 43 61 bb\n\
         79 2f 77 33 6d 01 61 15 63 63 65 a3 8f 01 01 15\n\
         77 e3 3b 25 fd 81 5d 73 43 77 39 53 93 41 d1 39\n\
         73 ad cb 3f 77 21 00 02 00 00 00 09 00 00 00 01\n\
         00 00 00 02 00 00 00 20 00 00 00 e0 17         \n",
        hex_builder.trim_end()
    );
    
    let data = hex_string_to_byte_array(&hex_string)?;
    
    println!("数据包长度: {} 字节", data.len());
    println!("准备发送广播到: {}", broadcast_addr);
    println!("绑定地址: {}", bind_addr);
    
    let packet_sent = socket.send_to(&data, broadcast_addr)?;
    
    println!("广播数据已发送到端口 {} ({} 字节)", port, packet_sent);
    
    Ok(())
}

fn hex_string_to_byte_array(hex_string: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut result = Vec::new();
    
    // 移除所有空白字符（包括换行符）
    let cleaned: String = hex_string.chars().filter(|c| !c.is_whitespace()).collect();
    
    // 按两个字符一组解析
    for i in (0..cleaned.len()).step_by(2) {
        if i + 1 >= cleaned.len() {
            break;
        }
        
        let hex_byte = &cleaned[i..i+2];
        let byte = u8::from_str_radix(hex_byte, 16)?;
        result.push(byte);
    }
    
    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_hex_string_to_byte_array() {
        let hex_str = "f7 30 93 00";
        let result = hex_string_to_byte_array(hex_str).unwrap();
        assert_eq!(result, vec![0xf7, 0x30, 0x93, 0x00]);
    }
    
    #[test]
    fn test_hex_string_with_newlines() {
        let hex_str = "f7 30\n93 00";
        let result = hex_string_to_byte_array(hex_str).unwrap();
        assert_eq!(result, vec![0xf7, 0x30, 0x93, 0x00]);
    }
}